<?php


namespace App\Service\Query\Admin\System;


use App\Common\CacheNameManager;
use App\Models\System\SystemMenuModel;
use App\Models\System\SystemRoleModel;
use App\Service\Query\Common\CommonQuery;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;

class MenuQueryService
{
    use CommonQuery;


    public function __construct(SystemMenuModel $model)
    {
        $this->model = $model;
    }


    public function index()
    {
        $lists = Cache::get(CacheNameManager::MENU_TREE);
        if (empty($lists)) {
            $lists = $this->getTreeMenu(0);
            Cache::put(CacheNameManager::MENU_TREE, $lists);
        }

        return $lists;
    }


    /**
     * 获取前三级菜单
     * @return array
     */
    public function getThreeMenu()
    {
        $authIds = [];
        $roleIds = session('roleIds');

        //顶级菜单
        $topQuery = $this->model->where(['pid' => 0, 'nav' => 1,'status'=>1]);
        if (in_array(SystemRoleModel::SUPER_ADMIN,$roleIds)) {
            $topMenus = $topQuery->orderBy('sort')->get(['id', 'title']);
        } else {
            $authIds = session('auth');
            $topMenus = $topQuery->whereIn('id', $authIds)->orderBy('sort')->get(['id', 'title']);
        }
        $topMenus = $topMenus->toArray();
        $twoThreeMenus = [];

        //二级菜单
        foreach ($topMenus as $topMenu) {

            if (in_array(SystemRoleModel::SUPER_ADMIN,$roleIds)) {
                $twoThreeMenus[$topMenu['id']] = $this->model->where(['pid' => $topMenu['id'], 'nav' => 1])->orderBy('sort')->get(['id', 'title', 'pid','icon'])->toArray();
            } else {
                $twoThreeMenus[$topMenu['id']] = $this->model->where(['pid' => $topMenu['id'], 'nav' => 1])->whereIn('id', $authIds)->orderBy('sort')->get(['id', 'title', 'pid','icon'])->toArray();
            }


            //三级菜单
            foreach ($twoThreeMenus[$topMenu['id']] as $key => $menu) {

                if (in_array(SystemRoleModel::SUPER_ADMIN,$roleIds)) {
                    $twoThreeMenus[$topMenu['id']][$key]['child'] = $this->model->where(['pid' => $menu['id'], 'nav' => 1])->orderBy('sort')->get(['id', 'title', 'url','icon'])->toArray();
                } else {
                    $twoThreeMenus[$topMenu['id']][$key]['child'] = $this->model->where(['pid' => $menu['id'], 'nav' => 1])->whereIn('id', $authIds)->orderBy('sort')->get(['id', 'title', 'url','icon'])->toArray();
                }
            }
        }

        //要单独取出首页的菜单
        $firstMenu = $this->model->where(['url' => '/'])->first()->toArray();

        return [
            'topMenus' => $topMenus,
            'twoThreeMenus' => $twoThreeMenus,
            'firstMenu' => $firstMenu,
        ];

    }

    //获取树型结构
    protected function getTreeMenu($pid = 0)
    {
        $fields = ['id', 'title', 'module'];

        $menus = $this->model->whereStatus(1)->wherePid($pid)->orderBy('sort')->get($fields);

        if ($menus->isEmpty()) {
            return [];
        }

        foreach ($menus as &$menu) {
            $menu['children'] = $this->getTreeMenu($menu->id);
            $menu['spread'] = true;  //展开

        }

        return $menus;
    }

    public function getMenuOption($menus, $id, $level = 0)
    {
        $str = '';

        foreach ($menus as $menu) {

            $tempLevel = $level;
            $title = $menu->title;

            if ($level > 0) {
                $title = '--' . $title;
            }
            while ($tempLevel--) {
                $title = '&nbsp;&nbsp;' . $title;
            }


            if ($menu->id == $id) {
                $str .= '<option level="' . $level . '" value="' . $menu->id . '" selected>' . $title . '</option>';
            } else {
                $str .= '<option level="' . $level . '" value="' . $menu->id . '">' . $title . '</option>';
            }

            if (isset($menu['children'])) {
                $tempStr = $this->getMenuOption($menu['children'], $id, $level + 1);

                $str = $str . $tempStr;
            }

        }

        return $str;
    }


    public function getMenuCheck(&$menus, $ids = [])
    {
        foreach ($menus as &$menu) {

            $menu['name'] = $menu->title;
            $menu['value'] = $menu->id;
            if (in_array($menu->id, $ids)) {
                $menu['checked'] = true;
            } else {
                $menu['checked'] = false;
            }
            $menu['disabled'] = false;

            if (!empty($menu['children'])) {
                $this->getMenuCheck($menu['children'], $ids);
                $menu['list'] = $menu['children'];
                unset($menu['children']);
            }
            unset($menu->title);
            unset($menu->id);

        }
    }

    //获取url对应id的数组
    public function getUrlToId()
    {
        $menus = Cache::get(CacheNameManager::MENU_URL_ID);
        if (empty($menus)) {
            $menus = $this->pluckToArray('id','url');
            Cache::put(CacheNameManager::MENU_URL_ID,$menus);
        }

        return $menus;
    }

}